package com.pig.service.impl;

import com.pig.entity.Order;
import com.pig.entity.OrderItem;
import com.pig.mapper.OrderItemMapper;
import com.pig.mapper.OrderMapper;
import com.pig.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional
    public Order createOrder(Order order) {
        // 设置订单时间和初始状态
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(0); // 0-待支付
        // 插入订单主表
        orderMapper.insert(order);
        //一人一单逻辑

        // 插入订单明细表
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            for (OrderItem item : order.getItems()) {
                item.setOrderId(order.getId());
            }
            orderItemMapper.insertBatch(order.getItems());
        }
        return order;
    }

    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.selectByUserId(userId);
    }

    @Override
    public Order getOrderDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
            order.setItems(items);
        }
        return order;
    }

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.selectAll();
    }
} 